package com.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.forum.mapper.*;
import com.forum.pojo.ForumArticle;
import com.forum.pojo.ForumArticleAttachment;
import com.forum.pojo.StudentInfo;
import com.forum.pojo.TeacherInfo;
import com.forum.pojo.vo.ArticleModify;
import com.forum.pojo.vo.ArticleModify2;
import com.forum.pojo.vo.FriendMessageVo;
import com.forum.result.Result;
import com.forum.service.ForumArticleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 86152
 * @description 针对表【forum_article(文章信息)】的数据库操作Service实现
 * @createDate 2023-01-31 00:42:33
 */
@Service
public class ForumArticleServiceImpl extends ServiceImpl<ForumArticleMapper, ForumArticle>
        implements ForumArticleService {
    @Autowired
    private ForumArticleMapper forumArticleMapper;
    @Autowired
    private ForumArticleAttachmentMapper forumArticleAttachmentMapper;
    @Autowired
    private TeacherInfoMapper teacherInfoMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Autowired
    private OssServiceImpl ossService;
    @Autowired
    private ForumCommentMapper forumCommentMapper;
    @Autowired
    private LikeRecordMapper likeRecordMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;


    /**
     * 通过主题和寻找类型寻找话题广场文章
     *
     * @param theme
     * @param findType
     * @return
     */

    @Override
    public List<ArticleModify> find0BoardEssay(String theme, String findType) {
        List<ForumArticle> boardEssay = forumArticleMapper.find0BoardEssay(theme, findType);
        List<ArticleModify> articleModifies = new ArrayList<>();
        for(ForumArticle item:boardEssay){
            ArticleModify articleModify = new ArticleModify();
            articleModify.setForumArticle(item);
            Long userId = item.getUserId();
            Integer integer = forumArticleMapper.selectIdentity(userId);
            articleModify.setIdentity(integer);
            articleModify.setAvatorUrl(forumArticleMapper.findAvartarUrlByUserId(userId));
            articleModifies.add(articleModify);
        }
        return articleModifies;
    }

    @Override
    public Page find1BoardEssay(Long pageNum, Long pageSize, String theme, Integer findType) {
        QueryWrapper<ForumArticle> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(theme)){
            queryWrapper.like("tag",theme);
        }
        queryWrapper.orderByDesc("top_type");
        if(findType==0){
            queryWrapper.orderByDesc("post_time");
        }else{
            queryWrapper.orderByDesc("good_count");
        }
        queryWrapper.eq("p_board_id",1);
        //创建一个分页的对象
        List<ForumArticle> forumArticles = forumArticleMapper.selectList(queryWrapper);
        List<ArticleModify2> packge = find1Packge(forumArticles);
        int limit= pageSize.intValue();
        int current= pageNum.intValue();
        Page pages = getPages(current, limit, packge);
//        Page<ForumArticle> page=new Page<ForumArticle>(pageNum,pageSize);
        return pages;
    }
    private List<ArticleModify2> find1Packge(List<ForumArticle> list){
        ArrayList<ArticleModify2> articleModify2s = new ArrayList<>();
        for(ForumArticle listItem:list){
            ArticleModify2 articleModify2 = new ArticleModify2();
            articleModify2.setForumArticle(listItem);
            Long userId = listItem.getUserId();
            String title = teacherInfoMapper.selectTitleById(userId);
            articleModify2.setTeacherTitle(title);
            articleModify2s.add(articleModify2);
        }
        return articleModify2s;
    }
    private Page getPages(Integer currentPage, Integer pageSize, List list){

        Page page = new Page();

        int size = list.size();
        if(size==0){
            return null;
        }
        if(pageSize > size){
            pageSize = size;
        }

        //求出最大页数，防止currentPage越界
        int maxPage = size % pageSize == 0 ? (size / pageSize) : (size / pageSize) + 1;

        if(currentPage > maxPage){
            currentPage = maxPage;
        }

        //当前页第一条数据下标
        int curIds = currentPage > 1 ? (currentPage -1) * pageSize : 0;

        List pageList = new ArrayList<>();

        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get(curIds + i));
        }

        page.setCurrent(currentPage).setSize(pageSize).setTotal(list.size()).setRecords(pageList);

        return page;

    }
    @Override
    public Result getPersonArticle(Long userId) {
        QueryWrapper<ForumArticle> forumArticleQueryWrapper=new QueryWrapper<>();
        forumArticleQueryWrapper.eq("user_id",userId);
        return Result.ok(forumArticleMapper.selectList(forumArticleQueryWrapper));
    }

    @Override
    public Result selectBoardEssay(String title, String tag,Integer findType, Long pageNum, Long pageSize,Integer pBoardId) {
        QueryWrapper<ForumArticle> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(tag))
        if(StringUtils.isNotEmpty(tag)){
            queryWrapper.like("tag",tag);
        }

        queryWrapper.eq("p_board_id",pBoardId);
        if(StringUtils.isNotEmpty(title)||StringUtils.isNotEmpty(tag)){
            queryWrapper.like("title",title);

        }
        queryWrapper.orderByDesc("top_type");
        if(findType==0){
            queryWrapper.orderByDesc("post_time");
        }else{
            queryWrapper.orderByDesc("good_count");
        }

        Page<ForumArticle> page=new Page<>(pageNum,pageSize);
        return Result.ok(forumArticleMapper.selectPage(page,queryWrapper));
    }

    @Override
    public int setStar(String articleId, Integer type) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("article_id",articleId);
        ForumArticle forumArticle = forumArticleMapper.selectOne(queryWrapper);
        forumArticle.setStar(type);
        return forumArticleMapper.updateById(forumArticle);
    }

    @Override
    public int setTop(String articleId, Integer type) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("article_id",articleId);
        ForumArticle forumArticle = forumArticleMapper.selectOne(queryWrapper);
        forumArticle.setTopType(type);
        return forumArticleMapper.updateById(forumArticle);
    }

    @Override
    public void postArticle(ForumArticle forumArticle, ForumArticleAttachment forumArticleAttachment, String[] fileUrls) {
        String random = RandomStringUtils.random(10, true, true);
        forumArticle.setArticleId(random);
        forumArticle.setPostTime(new Date());
        forumArticle.setLastUpdateTime(new Date());
        if (fileUrls != null) {
            this.uploadAttachment(forumArticle, forumArticleAttachment, fileUrls);
        }
        forumArticleMapper.insert(forumArticle);
        //更新用户的相关信息
    }

    /**
     * 为实现完全
     *
     * @param article
     * @param attachment
     * @param fileUrls
     */
    public void uploadAttachment(ForumArticle article, ForumArticleAttachment attachment, String[] fileUrls) {
        //set userId  filetype还没加可以删掉这个字段
        attachment.setFileId(RandomStringUtils.random(10, true, true));
        attachment.setArticleId(article.getArticleId());
        attachment.setDownloadCount(0);
        attachment.setUserId(article.getUserId());
        //处理fileUrls为一个
        String filepath = "";
        for (int i = 0; i < fileUrls.length; i++) {
            if (i < fileUrls.length - 1) {
                filepath += fileUrls[i] + ",";
            } else {
                filepath += fileUrls[i];
            }
        }
        attachment.setFilePath(filepath);
        forumArticleAttachmentMapper.insert(attachment);
    }

    @Override
    public ForumArticle selectByArticleId(String articleId) {
        return forumArticleMapper.selectByArticleId(articleId);
    }

    /**
     * 阅读文章自增阅读量
     *
     * @param articleId
     */
    @Override
    public void readArticle(String articleId) {
        this.forumArticleMapper.updateArticleCount(0, 1, articleId);
    }

    /**
     * 寻找文章user昵称
     * @param userId
     */
    @Override
    public String findNickNameByUserId(Long userId) {
        return forumArticleMapper.findNickNameByUserId(userId);
    }

    @Override
    public String selectAvatarByUserId(Long userId) {
        return forumArticleMapper.findAvartarUrlByUserId(userId);
    }

    @Override
    public Page<ForumArticle> findAllByPage(Integer pageNo, Integer pageSize) {
        return null;
    }

    @Override
    public List<FriendMessageVo> selectPerson(String nickName) {
        List<FriendMessageVo> friendMessageVos = new ArrayList<>();
        QueryWrapper<StudentInfo> studentInfoQueryWrapper = new QueryWrapper<>();
        studentInfoQueryWrapper.like("nickName",nickName);
        List<StudentInfo> list1 = studentInfoMapper.selectList(studentInfoQueryWrapper);
        QueryWrapper<TeacherInfo> teacherInfoQueryWrapper = new QueryWrapper<>();
        teacherInfoQueryWrapper.like("nickName",nickName);
        List<TeacherInfo> list2 = teacherInfoMapper.selectList(teacherInfoQueryWrapper);
        messagePackage(list1,list2,friendMessageVos);
        return friendMessageVos;
    }

    private void messagePackage(List<StudentInfo> list1, List<TeacherInfo> list2, List<FriendMessageVo> friendMessageVos) {
        for(TeacherInfo listItem:list2){
            FriendMessageVo friendMessageVo = new FriendMessageVo();
            Long teacherid = listItem.getTeacherid();
            friendMessageVo.setUserId(listItem.getTeacherid());
            friendMessageVo.setNickName(listItem.getNickname());
            friendMessageVo.setArticleCount(getUserArticleCount(teacherid));
            friendMessageVo.setSignature(listItem.getSignature());
            friendMessageVo.setAvatarUrl(listItem.getAvartarurl());
            friendMessageVo.setCommentCount(getUserCommentCount(teacherid));
            friendMessageVo.setIdentity(Integer.valueOf(listItem.getIdentity()));
            friendMessageVo.setGoodCount(getUserLikeCount(teacherid));
            friendMessageVos.add(friendMessageVo);
        }
        for(StudentInfo listItem:list1){
            FriendMessageVo friendMessageVo = new FriendMessageVo();
            Long studentid = listItem.getStudentid();
            friendMessageVo.setUserId(studentid);
            friendMessageVo.setNickName(listItem.getNickname());
            friendMessageVo.setArticleCount(getUserArticleCount(studentid));
            friendMessageVo.setSignature(listItem.getSignature());
            friendMessageVo.setAvatarUrl(listItem.getAvartarurl());
            friendMessageVo.setCommentCount(getUserCommentCount(studentid));
            friendMessageVo.setIdentity(Integer.valueOf(listItem.getIdentity()));
            friendMessageVo.setGoodCount(getUserLikeCount(studentid));
            friendMessageVos.add(friendMessageVo);
        }
    }
    /**
     * 获取评论的数量
     *
     * @param userId
     * @return
     */
    private Integer getUserCommentCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return forumCommentMapper.selectCount(queryWrapper);
    }

    /**
     * 获取好友点赞过的数量
     *
     * @param userId
     * @return
     */
    private Integer getUserLikeCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return likeRecordMapper.selectCount(queryWrapper);
    }

    /**
     * 获取好友发布的贴子
     *
     * @param userId
     * @return
     */
    private Integer getUserArticleCount(Long userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        return forumArticleMapper.selectCount(queryWrapper);
    }
    @Override
    @Transactional(rollbackFor = {Exception.class}, readOnly = false)
    public boolean deleteByArticleId(String articleId) {
        userMessageMapper.deleteByArticleId(articleId);
        return removeById(articleId);
    }

    @Override
    public Integer selectIdentityByUserId(Long userId) {
        return forumArticleMapper.selectIdentity(userId);
    }
}




